package com.powernode.bank.service.Impl;

import com.powernode.bank.mapper.AccountMapper;
import com.powernode.bank.pojo.Account;
import com.powernode.bank.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional
@Service("accountService")
public class AccountServiceImpl implements AccountService {
    @Autowired
    private AccountMapper accountMapper;

    @Override
    public int save(Account account) {
        return accountMapper.insert(account);
    }

    @Override
    public int deletedByAccno(String accno) {
        return accountMapper.deleteByAccno(accno);
    }

    @Override
    public int modify(Account account) {
        return accountMapper.update(account);
    }

    @Override
    public Account selectByAccno(String accno) {
        return accountMapper.selectByAccno(accno);
    }

    @Override
    public List<Account> selectAll() {
        return accountMapper.selectAll();
    }

    @Override
    public void transfer(String fromAccno, String toAccno, double amount) {
        Account fromAccount = accountMapper.selectByAccno(fromAccno);
        Account toAccount = accountMapper.selectByAccno(toAccno);
        if (fromAccount == null || toAccount == null) {
            throw new RuntimeException("用户不存在,转账异常!!");
        }
        if (fromAccount.getBalance() < amount) {
            throw new RuntimeException("余额不足，转账异常!!");
        }
        fromAccount.setBalance(fromAccount.getBalance() - amount);
        toAccount.setBalance(toAccount.getBalance() + amount);
        int count = accountMapper.update(fromAccount);
        count += accountMapper.update(toAccount);
        if (count != 2) {
            throw new RuntimeException("转账异常!!");
        }
    }
}
